<?php

namespace app\common\model\banxi\student;

use app\common\enums\AppointmentStatusEnum;
use app\common\enums\CoreCourseTypeEnum;
use app\common\enums\CourseDeliveryTypeEnum;
use app\common\enums\CourseFullTypeEnum;
use app\common\enums\StudentAppointmentStatusEnum;
use app\common\model\banxi\core\CoreCourseAppointment;
use app\common\model\banxi\organization\Organization;
use app\common\model\banxi\student\Student;
use app\common\model\banxi\trainer\Trainer;
use app\common\model\common\BaseModel;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Db;
use think\model\concern\SoftDelete;

/**
 * 学生课程预约
 */
class StudentCourseAppointment extends BaseModel
{
    use SoftDelete;

    protected $name = 'banxi_student_course_appointment';

    protected $autoWriteTimestamp = true;

    protected $deleteTime = 'del';

    protected $defaultSoftDelete = 0;

    protected $append = [
        'appointmentStatusCn',
        'courseDeliveryTypeCn',
        'courseFullTypeCn',
        'courseTypeCn'
    ];

    protected $type = [
        'id' => 'string',
        'del' => 'string',
        'courseId' => 'string',
        'studentId' => 'string',
        'trainerId' => 'string',
        'createTime' => 'timestamp:Y-m-d H:i:s',
        'updateTime' => 'timestamp:Y-m-d H:i:s',
    ];

    //-----------------------------------------------------------------------------------
    //｜                                   获取器                                       ｜
    //-----------------------------------------------------------------------------------

    public function getAppointmentStatusCnAttr($value, $data)
    {
        $value = $value ?: ($data['appointmentStatus'] ?? '');
        return (new StudentAppointmentStatusEnum())->getDescription($value) ?? '';
    }

    public function getCourseDeliveryTypeCnAttr($value, $data)
    {
        $value = $value ?: ($data['courseDeliveryType'] ?? '');
        return (new CourseDeliveryTypeEnum())->getDescription($value) ?? '';
    }

    public function getCourseFullTypeCnAttr($value, $data)
    {
        $value = $value ?: ($data['courseFullType'] ?? '');
        return (new CourseFullTypeEnum())->getDescription($value) ?? '';
    }

    public function getCourseTypeCnAttr($value, $data)
    {
        $value = $value ?: ($data['courseType'] ?? '');
        return (new CoreCourseTypeEnum())->getDescription($value) ?? '';

    }

    //-----------------------------------------------------------------------------------
    //｜                                  处理方法                                       ｜
    //-----------------------------------------------------------------------------------

    public function getListPage(array $where, string $page = "1", int $limit = 10)
    {
        return $this->with([
            'trainerInfo' => function ($query) {
                $query->field('id,name');
            }])->order(['id' => 'desc'])->where($where)->paginate(['page' => $page, 'list_rows' => $limit]);
    }

    /*
     * 处理预约
     * @param $id 预约id
     * @param $trainerId 教练id
     * @param $status 处理状态
     * @return true
     * */
    public function handleAppointment(int $id, int $trainerId, int $status)
    {
        Db::startTrans();
        try {
            $appointmentInfo = self::where(['id'=>$id,'trainerId'=>$trainerId])->find();
            if (!$appointmentInfo) {
                throw new ValidateException('预约信息不存在');
            }
            if ($appointmentInfo['appointmentStatus'] != StudentAppointmentStatusEnum::E1) {
                throw new ValidateException('预约已处理');
            }
            if ($status == 1){//接受
                //创建排课预约
                $data = [
                    'trainerId'=>$appointmentInfo['trainerId'],
                    'studentId'=>$appointmentInfo['studentId'],
                    'studentOrganizationId'=>$appointmentInfo['studentOrganizationId'],
                    'date'=>$appointmentInfo['date'],
                    'startTime'=>$appointmentInfo['startTime'],
                    'endTime'=>$appointmentInfo['endTime'],
                    'courseType'=>$appointmentInfo['courseType'],
                    'courseId'=>$appointmentInfo['courseId'],
                    'courseName'=>$appointmentInfo['courseName'],
                    'courseFullType'=>$appointmentInfo['courseFullType'],
                    'courseDeliveryType'=>$appointmentInfo['courseDeliveryType'],
                    'isStudentAppointment'=>1
                ];
                $CoreCourseAppointmentModel = new CoreCourseAppointment();
                $CoreCourseAppointmentModel->save($data);
                $appointmentInfo->save(['appointmentStatus'=>StudentAppointmentStatusEnum::E2]);
            }elseif ($status == 2){//拒绝
                $appointmentInfo->save(['appointmentStatus'=>StudentAppointmentStatusEnum::E3]);
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            throw new ValidateException($e->getMessage());
        }
        return true;
    }

    //-----------------------------------------------------------------------------------
    //｜                                   模型关联                                       ｜
    //-----------------------------------------------------------------------------------


    public function trainerInfo()
    {
        return $this->hasOne(Trainer::class, 'id', 'trainerId');
    }

    public function studentInfo()
    {
        return $this->hasOne(Student::class, 'id', 'studentId');
    }

}